<template>
  <div id="user">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->

    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" v-model="params.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
        <!-- 表格区域 -->
        <el-table :data="userList" stripe border>
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#409eff"
                @change="userStateChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <!-- {{scope.row}}通过作用域插槽，可以获得对应信息 -->
              <el-button
                type="primary"
                @click="editUserInfo(scope.row.id)"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delUserInfo(scope.row.id)"
              ></el-button>
              <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRoleBtn(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <!-- 页码功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 增加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 表单输入区域 -->
      <el-form ref="addRules" :model="addFormRules" :rules="addRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFormRules.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addFormRules.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model="addFormRules.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addFormRules.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">新 增</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeEditDialog"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="ruleForm"
        label-width="100px"
        class="editForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfoBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置角色对话框 -->
    <el-dialog title="设置角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleClose">
      <div class="div">
        <p>当前的用户：{{roleInfo.username}}</p>
        <p>当前的角色：{{roleInfo.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRole" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      params: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      addFormRules: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户信息对话框显示隐藏
      editDialogVisible: false,
      // 通过id获取到修改用户信息
      editForm: {},
      // 控制设置角色框的显示隐藏
      setRoleDialogVisible: false,
      // 当前角色数据
      roleInfo: {},
      // 角色的列表
      rolesList: [],
      // 选中的角色
      selectRole: ''
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.params
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(this.userList)
    },
    // 检测显示条数变化时获取选项
    handleSizeChange (newShowPage) {
      // console.log(newShowPage)
      this.params.pagesize = newShowPage
      this.getUsersList()
    },
    // 点击页码时获取变化值
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.params.pagenum = newPage
      this.getUsersList()
    },
    // 监听switch的变化数据
    async userStateChange (userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听对话框关闭的时候，清除输入内容
    addDialogClose () {
      this.$refs.addRules.resetFields()
    },
    addUser () {
      // 通过表单的validate方法，可以做表单预验证
      this.$refs.addRules.validate(async valid => {
        if (!valid) return this.$message('添加失败1')
        // 通过验证，可以发送添加请求
        const { data: res } = await this.$http.post('/users', this.addFormRules)
        console.log(res.meta)
        if (res.meta.status !== 201) return this.$message('添加失败')

        this.$message('添加成功')
        this.addDialogVisible = false
        this.getUsersList()
      })
    },
    // 修改用户信息
    async editUserInfo (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message('查询失败')
      this.editForm = res.data
      // 显示对话框
      this.editDialogVisible = true
    },
    // 关闭修改用户框时还原对话框数据
    closeEditDialog () {
      this.$refs.ruleForm.resetFields()
    },
    // 修改用户信息预校验及put数据上传
    editUserInfoBtn () {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return this.$message.error('请输入正确的信息')
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('用户信息更新失败')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新用户列表数据
        this.getUsersList()
        // 提示用户更新成功
        this.$message.success('用户数据更新成功')
      })
    },
    // 删除用户
    async delUserInfo (id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err) // 直接返回err
      // 点击确定，则返回confirm
      if (confirmRes !== 'confirm') {
        return this.$message.info('已经取消删除')
      }

      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }

      this.$message.success('删除成功')
      this.getUsersList()
    },
    async setRoleBtn (roleInfo) {
      this.roleInfo = roleInfo

      // 获取角色列表
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.message.error('获取角色列表失败')
      }

      this.rolesList = res.data

      // console.log(res)
      this.setRoleDialogVisible = true
    },
    async editRole () {
      if (!this.selectRole) {
        return this.$message.info('请选择新的角色')
      }

      const { data: res } = await this.$http.put(
        `users/${this.roleInfo.id}/role`,
        { rid: this.selectRole }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('更新失败！' + res.meta.msg)
      }

      this.setRoleDialogVisible = false
      this.$message.success('更新成功')
    },
    setRoleClose () {
      this.selectRole = ''
    }
  }
}
</script>

<style>
</style>
